package com.maya.medicalwastes.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.inputmethodservice.ExtractEditText;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.maya.medicalwastes.CollectActivity;
import com.maya.medicalwastes.LoginActivity;
import com.maya.medicalwastes.ParamConstant;
import com.maya.medicalwastes.R;
import com.maya.medicalwastes.adapter.WaitWareAdapter;
import com.maya.medicalwastes.dialog.LoadingDialog;
import com.maya.medicalwastes.dialog.SureCollectDialog;
import com.maya.medicalwastes.dialog.UploadErrorDialog;
import com.maya.medicalwastes.entity.CollectBean;
import com.maya.medicalwastes.entity.KeyBean;
import com.maya.medicalwastes.entity.WaitWareBean;
import com.maya.medicalwastes.httpNet.ApiService;
import com.maya.medicalwastes.httpNet.HttpService;
import com.maya.medicalwastes.httpNet.callback.ResponseCallBack;
import com.maya.medicalwastes.httpNet.common.SharedPreferencesConstant;
import com.maya.medicalwastes.httpNet.manage.RetrofitManager;
import com.maya.medicalwastes.httpNet.model.ResultModel;
import com.maya.medicalwastes.util.FormatUtilA;
import com.maya.medicalwastes.util.PrefUtils;
import com.maya.medicalwastes.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;

public class WarehouseActivity extends AppCompatActivity {
    @BindView(R.id.et_scan_numb)
    ExtractEditText scanNumb;
    //待入库
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    //确认入库
    @BindView(R.id.recyclerview1)
    RecyclerView mRecyclerView1;

    @BindView(R.id.btn_sure)
    Button btnOk;
    @BindView(R.id.tv_numb)
    TextView tv_numb;
    @BindView(R.id.tv_left)
    TextView tv_left;
    @BindView(R.id.tv_left_numb)
    TextView tv_left_numb;
    @BindView(R.id.tv_weight)
    TextView tv_weight;
    @BindView(R.id.tv_one_key)
    TextView tv_one_key;
    @BindView(R.id.tv_title)
    TextView tv_title;
    WaitWareAdapter adapter;
    WaitWareAdapter adapter1;
    private Double weight = 0.0;
    private List<CollectBean> mWaitWareBeanList = new ArrayList<>();
    private List<CollectBean> mWaitWareBeanList1 = new ArrayList<>();
    private String abnormalDictionary = "";
    UploadErrorDialog uploadErrorDialog;
    SureCollectDialog sureCollectDialog;
    private String id;
    private String warehouse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_warehouse);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        tv_title.setText("入库");
        if (bundle != null) {
            id = bundle.getString("ID", "");
            warehouse = bundle.getString("warehouse", "");
        }
        adapter = new WaitWareAdapter(R.layout.list_waitwaste_item, mWaitWareBeanList);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(adapter);

        adapter1 = new WaitWareAdapter(R.layout.list_waitwaste_item, mWaitWareBeanList1);
        mRecyclerView1.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView1.setAdapter(adapter1);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_state) {
                    CollectBean collectBean = (CollectBean) adapter.getData().get(position);
                    uploadErrorDialog = new UploadErrorDialog(WarehouseActivity.this, collectBean.getGarbageId());
                    uploadErrorDialog.setOnBtnClickListener(new UploadErrorDialog.OnBtnClickListener() {
                        @Override
                        public void onOkClick(String type, String string) {
                            keySearch(type);
                            updateAbnormalReporting(collectBean, string);

                        }

                        @Override
                        public void onCancelClick() {

                        }
                    });
                    uploadErrorDialog.popDialog();
                }
            }
        });
        tv_one_key.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                weight=0.0;
                if (mWaitWareBeanList.size() > 0) {
                    mWaitWareBeanList1.clear();
                    mWaitWareBeanList1.addAll(mWaitWareBeanList);
                    mWaitWareBeanList.clear();
                    adapter.replaceData(mWaitWareBeanList);
                    adapter1.notifyDataSetChanged();

                    for (CollectBean collectBean : mWaitWareBeanList1) {
                        weight += Double.parseDouble(collectBean.getWeight());
                    }
                    tv_numb.setText(mWaitWareBeanList1.size() + "件");
                    tv_weight.setText(FormatUtilA.numbFormat(weight) + "kg");
                    tv_left.setText("");
                    tv_left_numb.setText("0件");
                    scanNumb.setText("0kg");
                } else {
                    ToastUtils.ViewToast(WarehouseActivity.this, "暂无入库的数据");
                    return;
                }
            }
        });
        waitWarehousingList();
        initOnclick();
    }

    private void initOnclick() {
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mWaitWareBeanList1.size() == 0) {
                    ToastUtils.ViewToast(WarehouseActivity.this, "暂无入库数据");
                    return;
                }
                sureCollectDialog = new SureCollectDialog(WarehouseActivity.this);
                sureCollectDialog.setOnBtnClickListener(new SureCollectDialog.OnBtnClickListener() {
                    @Override
                    public void onOkClick(String base, boolean flag) {
                        if (flag){
                            save(base);
                        }else {
                            ToastUtils.ViewToast(WarehouseActivity.this,"您还没有签名");
                            return;
                        }
                    }

                    @Override
                    public void onCancelClick() {

                    }
                });
                sureCollectDialog.popDialog();
            }
        });
        adapter1.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_state) {
                    CollectBean collectBean = (CollectBean) adapter.getData().get(position);
                    uploadErrorDialog = new UploadErrorDialog(WarehouseActivity.this, collectBean.getGarbageId());
                    uploadErrorDialog.setOnBtnClickListener(new UploadErrorDialog.OnBtnClickListener() {
                        @Override
                        public void onOkClick(String type, String string) {
                            keySearch(type);
                            updateAbnormalReporting(collectBean, string);
                        }

                        @Override
                        public void onCancelClick() {

                        }
                    });
                    uploadErrorDialog.popDialog();
                }
            }
        });

        scanNumb.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                weight = 0.0;
                if (editable.toString().contains("=")) {
                    String[] str = editable.toString().split("_");
                    for (int i = 0; i < adapter.getData().size(); i++) {
                        if (adapter.getData().get(i).getGarbageId() != null) {
                            if (adapter.getData().get(i).getGarbageId().equals(str[1])) {
                                mWaitWareBeanList1.add(adapter.getData().get(i));
                                adapter.remove(i);
                                adapter1.notifyDataSetChanged();
                            }
                        }
                    }
                    for (CollectBean collectBean : mWaitWareBeanList1) {
                        weight += Double.parseDouble(collectBean.getWeight());
                    }
                    tv_numb.setText(mWaitWareBeanList1.size() + "件");
                    tv_weight.setText(FormatUtilA.numbFormat(weight) + "kg");
                    scanNumb.setText("");
                }
            }
        });


    }

    private void updateAbnormalReporting(CollectBean collectBean, String string) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("garbageId", collectBean.getGarbageId());
        param.put("abnormalInfo", string);
        param.put("reportPerson", PrefUtils.getString(WarehouseActivity.this, "authOrgId", ""));
        param.put("abnormalDictionary", abnormalDictionary);
        Observable<ResultModel<WaitWareBean>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).waitWarehousingList(param, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<WaitWareBean>>() {
            @Override
            public void onResponse(ResultModel<WaitWareBean> response) {
                if (response.httpCode == 200) {
                    ToastUtils.ViewToast(WarehouseActivity.this, "异常上报成功");
                } else {
                    ToastUtils.ViewToast(WarehouseActivity.this, "异常上报失败");

                }
                uploadErrorDialog.dismiss();
            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, this);


    }

    private void waitWarehousingList() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("collectCarId", "200");
        param.put("warehouseState", "1");
        Observable<ResultModel<WaitWareBean>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).waitWarehousingList(param, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<WaitWareBean>>() {
            @Override
            public void onResponse(ResultModel<WaitWareBean> response) {
                if(response.data.getList().size()>0){
                    mWaitWareBeanList = response.data.getList();
                    adapter.replaceData(mWaitWareBeanList);
                    for (CollectBean collectBean : mWaitWareBeanList) {
                        weight += Double.parseDouble(collectBean.getWeight());
                    }
                    tv_left.setText(mWaitWareBeanList.size() + "件");
                    tv_left_numb.setText(FormatUtilA.numbFormat(weight) + "kg");
                }

            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, this);
    }

    public void keySearch(String type) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("key", "CATEGORY");
        param.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        Observable<ResultModel<ArrayList<KeyBean>>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).Keyword(param);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<ArrayList<KeyBean>>>() {
            @Override
            public void onResponse(ResultModel<ArrayList<KeyBean>> response) {
                if (response != null && response.httpCode == 200) {
                    for (KeyBean d : response.data) {
                        if (d.getValue().equals(type)) {
                            abnormalDictionary = d.getKey();
                        }
                    }
                }
            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, this);
    }

    public void save(String base) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("warehousingSignPicture", base);
        param.put("warehouseID", id);
        param.put("warehouseAdmin", warehouse);
        param.put("data", mWaitWareBeanList1);
        Observable<ResultModel<String>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).updateWarehouseState(param, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<String>>() {
            @Override
            public void onResponse(ResultModel<String> response) {
                if (response != null && response.httpCode == 200) {
                    ToastUtils.ViewToast(WarehouseActivity.this, "上传成功");
                    mWaitWareBeanList1.clear();
                    tv_numb.setText(mWaitWareBeanList1.size() + "件");
                    weight = 0.0;
                    tv_weight.setText("0kg");
                    mWaitWareBeanList1.clear();
                    sureCollectDialog.dismiss();
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, this);

    }


}
